import { apiMsgProp } from '@/utils/global'
import http from './http'
import type { UnitItem, UnitItemCreate } from '@/types/unit'
import type { ResourceItem } from '@/types/resource'

const UnitService = {
    /**
     * @function list 获取单元列表
     * @param courseId 课程id
     * @returns UnitItem[] 单元列表
     */
    list: async (courseId?: number): Promise<UnitItem[]> => {
        const res = await http.get(`/course/unit/list?course_id=${courseId}`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }

        return res.data.data
            .map((item: UnitItem) => {
                item._resources = item.resources.reduce((acc: any, resource: ResourceItem) => {
                    if (!acc[resource.type]) {
                        acc[resource.type] = []
                    }
                    acc[resource.type].push(resource)
                    return acc
                }, {})

                return item
            })
            .sort((a: UnitItem, b: UnitItem) => a.sort_order - b.sort_order)
    },
    /**
     * @function getById 获取单元信息
     * @param id 单元id
     * @returns UnitItem 单元信息
     */
    getById: async (id: number): Promise<UnitItem> => {
        const res = await http.get(`/course/unit/${id}/info`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data
    },
    /**
     * @function save 保存单元信息
     * @param data 单元信息
     * @returns UnitItem 单元信息
     */
    save: async (data: UnitItemCreate): Promise<UnitItem> => {
        const _data: any = { ...data }
        if (_data.id == null) delete _data.id
        if (_data._resources) delete _data._resources

        const res = await http.post(`/course/unit/save`, data)

        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)

        return res.data.data
    },
    /**
     * @function sort 单元排序
     * @param data 单元排序信息
     * @returns void
     */
    sort: async (data: { id: number; sort_order: number }[]): Promise<void> => {
        const res = await http.post(`/course/unit/sort`, data)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
    },
    /**
     * @function delete 删除单元
     * @param id 单元id
     * @returns void
     */
    delete: async (id: number): Promise<void> => {
        const res = await http.delete(`/course/unit/${id}`)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
}

export default UnitService
